import React, { useState, useEffect } from 'react';
import { ck_float, KDlg, KInput, BtTxt, PanelTitle, WaitUmd, is_empty, uDb, cline, ck_empty, useKForm, KFind, save_data, useCmd,
    no_del, obj_float, Btn, GridTable, loc, Dlg } from 'sui';
import { load_try, save_try } from './cmd';

const DlgVal = ({ open, setOpen, data }) => {
    const umd = useCmd();

    const col = [
        {name: loc("l_802"), key: 'sn', width: 100},
        {name: loc("l_127"), key: 'num', width: 100},
    ];

    const hout = () => {
        save_data(data, col, loc("l_853"), umd);
    };

    return (
        <Dlg title={loc("l_853")} open={open} hcmd={() => setOpen(false)}>
            <div className="flex justify-end mr-2">
                <Btn hcmd={hout}>{loc("l_298")}</Btn>
            </div>
            <GridTable high={400} col={col} row={data}/>
        </Dlg>
    );
};

const DlgLog = ({ open, setOpen, data, mod="hc" }) => {
    const [main, setMain] = useState();
    const [lst_tech, lstTech] = useState();
    const form = useKForm();
    const umd = useCmd();

    useEffect(() => {
        if (!open || is_empty(data)) {
            return;
        }

        const lst = [];
        data.forEach(d => lst.push({ sn: d.sn, name: d.sn }));
        lstTech(lst);
    }, [open, data]);

    const hFind = () => {
        const ck = {
            tsn : v => ck_empty(v),
        };

        if (form.isErr(ck)) {
            return;
        }

        const tsn = form.get("tsn");

        umd.startWait();

        uDb(umd.endWait, `field/listnocache/${mod}_${tsn}`, { line: cline() },
            r => {
                const tmp = [];

                r.forEach((d, i) => {
                    tmp.push({
                        index: i + 1,
                        name: d,
                    });
                });

                setMain(tmp);
            },
            e => setMain(null));
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_228"), key: 'name', width: 800},
    ];

    const hout = () => {
        save_data(main, col, loc("l_862"), umd);
    };

    return (
        <Dlg title={loc("l_862")} open={open} hcmd={() => setOpen(false)} width="lg">
            <div className="flex justify-between mr-2">
                <div className="inline-flex items-center">
                    <Btn className="mr-4" color="green" hcmd={hFind}>{loc("l_551")}</Btn>
                    <KFind label={loc("l_694")} form={form} name="tsn" margin="dense" width="w-56" list={lst_tech}/>
                </div>
                <Btn hcmd={hout}>{loc("l_298")}</Btn>
            </div>
            <GridTable high={400} col={col} row={main}/>
        </Dlg>
    );
};

const DlgNum = (props) => {
    const form = useKForm();

    const ck = {
        dw : v => ck_float(v),
    };

    return (
        <KDlg {...props} title={loc("l_698")} ck={ck} form={form}>
            <KInput label={loc("l_698")} form={form} name="dw"/>
        </KDlg>
    );
};

const DlgDw = ({ open, setOpen }) => {
    const [open_num, openNum] = useState(false);
    const [cera, setCera] = useState();
    const [stell, setStell] = useState();
    const umd = useCmd();

    useEffect(() => {
        if (!open) {
            return;
        }

        load_try(null, "cera", setCera);
        load_try(null, "stell", setStell);
    }, [open]);

    const del = (v, tp, old, setNew) => {
        const dw = obj_float(v, "dw");
        const ret = [];

        old.forEach(d => {
            if (d.dw === dw) {
                return;
            }

            ret.push(d.dw);
        });

        umd.startWait();

        save_try(umd.endWait, tp, ret, setNew);
    };

    const hdel = (v, tp) => {
        if (no_del()) {
            return;
        }

        if (tp === "cera") {
            del(v, "cera", cera, setCera);
        } else if (tp === "stell") {
            del(v, "stell", stell, setStell);
        }
    };

    const add = (v, old, setNew) => {
        const dw = obj_float(v, "dw");
        const ret = [];

        if (!is_empty(old)) {
            old.forEach(d => ret.push(d.dw));
        }

        const f = ret.find(d => d === dw);
        if (f) {
            return;
        }

        ret.push(dw);

        umd.startWait();

        save_try(umd.endWait, umd.fin, ret, setNew);
    };

    const hadd = (v) => {
        if (umd.isFin("cera")) {
            add(v, cera, setCera);
        } else if (umd.isFin("stell")) {
            add(v, stell, setStell);
        }
    };

    const pact = {
        "cera": () => openNum(true),
        "stell": () => openNum(true),
    };

    const col_cera = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: `${loc("l_713")}${loc("l_802")}`, key: 'dw', width: 200},
        {name: loc("l_238"), key: 'e_opt', width: 200, formatter: (props) => {
            const d = props.row;
            return <BtTxt hcmd={() => hdel(d, "cera")}>{loc("l_237")}</BtTxt>;
        }},
    ];

    const col_stell = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: `${loc("l_712")}${loc("l_802")}`, key: 'dw', width: 200},
        {name: loc("l_238"), key: 'e_opt', width: 200, formatter: (props) => {
            const d = props.row;
            return <BtTxt hcmd={() => hdel(d, "stell")}>{loc("l_237")}</BtTxt>;
        }},
    ];

    const CeraRight = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(pact, null, "cera")}>{loc("l_239")}</Btn>
        </div>
    );

    const StellRight = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(pact, null, "stell")}>{loc("l_239")}</Btn>
        </div>
    );

    return (
        <Dlg title={loc("l_876")} open={open} hcmd={() => setOpen(false)} width="lg" labok={loc("l_287")}>
            <div className="w-full inline-flex">
                <div className="flex-row w-1/2">
                    <PanelTitle cl="green" left={loc("l_713")} right={<CeraRight/>}/>
                    <GridTable high={400} col={col_cera} row={cera}/>
                </div>
                <div className="flex-row w-1/2">
                    <PanelTitle cl="blue" left={loc("l_712")} right={<StellRight/>}/>
                    <GridTable high={400} col={col_stell} row={stell}/>
                </div>
            </div>
            <DlgNum open={open_num} setOpen={openNum} hcmd={hadd}/>
            <WaitUmd umd={umd}/>
        </Dlg>
    );
};

export {DlgDw, DlgLog, DlgVal};
